import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  InputNumber,
  Col,
  Row,
  DatePicker,
  Input,
  Select,
  message,
  Spin,
} from 'antd';
import router from 'umi/router';
import moment from 'moment';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { urlParse } from '@/utils/utils';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
@connect(({ laborcontract, loading }) => ({
  loading: loading.models.laborcontract,
  laborcontract,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1',
      isTimeRequired: true,
      isTryDateRequired: true,
      laborContId: '',
      empId: '',
      contSignWayList: [],
      empContTypeList: [],
      isNullFlagList: [],
      workHoursList: [],
      yesNoList: [],
      isHasFixedDate: '', // 记录原来数据是否有固定日期
      isHasTryDate: '', // 记录原来数据是否有试用期
      initialData: {}, // //记录原来数据
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    const { laborContId } = urlParse(location.search);
    const { empId } = urlParse(location.search);
    const { custId } = urlParse(location.search);
    const { activeKey } = urlParse(location.search);
    this.setState({ laborContId, empId, custId, activeKey });
    // 获取页签字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['CONT_SIGN_WAY', 'EMP_CONT_TYPE', 'ISNULL_FLAG', 'WORK_HOURS', 'YES_NO_FLAG'],
    }).then(res => {
      this.setState({
        contSignWayList: res.CONT_SIGN_WAY,
        empContTypeList: res.EMP_CONT_TYPE,
        isNullFlagList: res.ISNULL_FLAG,
        workHoursList: res.WORK_HOURS,
        yesNoList: res.YES_NO_FLAG,
      });
      this.getDetail(laborContId);
    });
  }

  // 获取数据
  getDetail = paramId => {
    const {
      location: { pathname },
      form,
      dispatch,
    } = this.props;
    const tempUrl = pathname.split('/change')[0];
    if (paramId) {
      dispatch({
        type: 'laborcontract/getEmpLaborCont',
        payload: {
          laborContId: paramId,
        },
      }).then(res => {
        if (res.success && res.data) {
          this.setState({ initialData: res.data });
          const response = res.data;
          const getFieldsList = form.getFieldsValue();
          // 判断是否显示固定期限
          if (response.fixedDeadlnFlag === '1') {
            this.setState({ isTimeRequired: true, isHasFixedDate: true });
          } else {
            this.setState({ isTimeRequired: false, isHasFixedDate: false });
            delete getFieldsList.contEndDate;
          }
          // 判断是否显示试用期
          if (response.probtnFlag === '1') {
            this.setState({ isTryDateRequired: true, isHasTryDate: true });
          } else {
            this.setState({ isTryDateRequired: false, isHasTryDate: false });
            delete getFieldsList.probtnBeginDate;
            delete getFieldsList.probtnEndDate;
          }
          Object.keys(response).forEach(key => {
            if (response[key]) {
              if (
                key === 'contSignWay' ||
                key === 'contType' ||
                key === 'fixedDeadlnFlag' ||
                key === 'probtnFlag' ||
                key === 'laborHour' ||
                key === 'entryMedExamFlag' ||
                key === 'signFlag'
              ) {
                response[key] = `${response[key]}`;
              }
            }
          });
          Object.keys(getFieldsList).forEach(key => {
            if (response[key]) {
              if (
                key === 'contBeginDate' ||
                key === 'contEndDate' ||
                key === 'probtnBeginDate' ||
                key === 'probtnEndDate' ||
                key === 'signDate'
              ) {
                form.setFieldsValue({ [key]: moment(response[key]) });
              } else {
                form.setFieldsValue({ [key]: response[key] });
              }
            }
          });
        } else {
          message.warning(`${res.message || '服务器端错误'}`);
        }
      });
    } else {
      router.push(`${tempUrl}/index`);
    }
  };

  // 选择有无固定期限
  changeTimeLimit = value => {
    const { form } = this.props;
    const { initialData } = this.state;
    if (value === '1') {
      form.setFieldsValue({
        contEndDate: initialData.contEndDate ? moment(initialData.contEndDate) : null,
      });
      this.setState({ isTimeRequired: true });
    } else {
      form.setFieldsValue({ contEndDate: null });
      this.setState({ isTimeRequired: false });
    }
  };

  // 选择有无试用期
  changeTryDate = value => {
    const { form } = this.props;
    const { initialData } = this.state;
    if (value === '1') {
      form.setFieldsValue({
        probtnBeginDate: initialData.probtnBeginDate ? moment(initialData.probtnBeginDate) : null,
        probtnEndDate: initialData.probtnEndDate ? moment(initialData.probtnEndDate) : null,
      });
      this.setState({ isTryDateRequired: true });
    } else {
      form.setFieldsValue({ probtnBeginDate: null, probtnEndDate: null });
      this.setState({ isTryDateRequired: false });
    }
  };

  disabledEndDate = (current, limitDate) => current && current < moment(limitDate).endOf('day');

  // 提交
  submitAll = () => {
    const {
      form,
      dispatch,
      location: { pathname },
    } = this.props;
    const { laborContId, empId, custId, activeKey } = this.state;
    const tempUrl = pathname.split('/change')[0];
    form.validateFieldsAndScroll((err, values) => {
      const temp = values;
      if (!err) {
        Object.keys(values).forEach(key => {
          if (
            key === 'contBeginDate' ||
            key === 'contEndDate' ||
            key === 'probtnBeginDate' ||
            key === 'probtnEndDate' ||
            key === 'signDate'
          ) {
            temp[key] = values[key] ? values[key].format('YYYY-MM-DD') : null;
          } else if (!values[key]) {
            temp[key] = null;
          } else if (values[key]) {
            if (key === 'probtnFlag' && values[key] && values[key] === '2') {
              // 如果没有试用期就没有试用期时间和试用期工资
              delete temp.probtnBeginDate;
              delete temp.probtnEndDate;
              delete temp.probtnWage;
            } else if (key === 'fixedDeadlnFlag' && values[key] === '2') {
              // 如果没有固定期限就没有合同结束时间
              delete temp.contEndDate;
            }
          }
        });

        temp.laborContId = laborContId;
        temp.empId = empId;
        temp.custId = custId;
        temp.sendAreaId = '140000';
        dispatch({
          type: 'laborcontract/empLaborContChange',
          payload: values,
        }).then(res => {
          if (res.success) {
            message.success('变更合同成功', 2, () => {
              router.push(`${tempUrl}/index?activeKey=${activeKey}`);
            });
          } else {
            message.warning(`${res.message || '变更合同失败！'}`);
          }
        });
      }
    });
  };

  // 渲染函数
  render() {
    const {
      loading,
      location: { pathname },
      form: { getFieldDecorator },
    } = this.props;
    const tempUrl = pathname.split('/change')[0];
    const {
      contSignWayList,
      empContTypeList,
      isNullFlagList,
      workHoursList,
      yesNoList,
      initialData,
      activeKey,
      isTimeRequired,
      isHasFixedDate,
      isTryDateRequired,
      isHasTryDate,
    } = this.state;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 字典下拉
    const dictOL = dictList =>
      dictList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin spinning={loading}>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>合同信息</span>}
              style={{ borderBottom: 'none' }}
            >
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="合同编号">
                    {getFieldDecorator('contNo', {
                      rules: [
                        {
                          required: false,
                          message: '最大长度不超过20的数字与字母组合',
                          pattern: /^[A-Za-z0-9]{1,20}$/,
                        },
                      ],
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="合同签署方式">
                    {getFieldDecorator('contSignWay', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <HOCSelect placeholder="请选择" showSearch disabled>
                        {dictOL(contSignWayList)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="合同类型">
                    {getFieldDecorator('contType', {
                      rules: [{ required: true, message: '请输入' }],
                    })(
                      <HOCSelect placeholder="请选择" showSearch disabled>
                        {dictOL(empContTypeList)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="有无固定期限">
                    {getFieldDecorator('fixedDeadlnFlag', {
                      rules: [{ required: true, message: '请输入' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        showSearch
                        onChange={this.changeTimeLimit}
                        disabled
                      >
                        {dictOL(isNullFlagList)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="合同开始日期">
                    {getFieldDecorator('contBeginDate', {
                      rules: [{ required: false, message: '请输入' }],
                      initialValue: initialData.contBeginDate
                        ? moment(initialData.contBeginDate)
                        : null,
                    })(
                      <DatePicker placeholder="合同开始日期" style={{ width: '100%' }} disabled />
                    )}
                  </FormItem>
                </Col>

                <Col {...colProps}>
                  <FormItem label="合同结束日期">
                    {getFieldDecorator('contEndDate', {
                      rules: [{ required: isTimeRequired, message: '请选择' }],
                      initialValue: initialData.contEndDate
                        ? moment(initialData.contEndDate)
                        : null,
                    })(
                      <DatePicker
                        placeholder="合同结束日期"
                        disabledDate={current =>
                          this.disabledEndDate(current, initialData.contBeginDate)
                        }
                        style={{ width: '100%' }}
                        getPopupContainer={trigger => trigger.parentNode}
                        disabled={!(isTimeRequired && !isHasFixedDate)} // 如果选择了有固定期限并且原始数据没有固定期限的时候 这个结束日期才可以选择
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="有无试用期">
                    {getFieldDecorator('probtnFlag', {
                      rules: [{ required: true, message: '请输入' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        showSearch
                        onChange={this.changeTryDate}
                        disabled
                      >
                        {dictOL(isNullFlagList)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="试用期开始日期">
                    {getFieldDecorator('probtnBeginDate', {
                      rules: [{ required: isTryDateRequired, message: '请选择' }],
                      initialValue: initialData.probtnBeginDate
                        ? moment(initialData.probtnBeginDate)
                        : null,
                    })(
                      <DatePicker
                        placeholder="试用期开始日期"
                        style={{ width: '100%' }}
                        getPopupContainer={trigger => trigger.parentNode}
                        disabled={!(isTryDateRequired && !isHasTryDate)} // 如果选择了有试用期并且原始数据没有试用期的时候 这个日期才可以选择
                      />
                    )}
                  </FormItem>
                </Col>

                <Col {...colProps}>
                  <FormItem label="试用期结束日期">
                    {getFieldDecorator('probtnEndDate', {
                      rules: [{ required: isTryDateRequired, message: '请选择' }],
                      initialValue: initialData.probtnEndDate
                        ? moment(initialData.probtnEndDate)
                        : null,
                    })(
                      <DatePicker
                        placeholder="试用期结束日期"
                        style={{ width: '100%' }}
                        getPopupContainer={trigger => trigger.parentNode}
                        disabled={!(isTryDateRequired && !isHasTryDate)} // 如果选择了有试用期并且原始数据没有试用期的时候 这个日期才可以选择
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="合同期劳动报酬">
                    {getFieldDecorator('contWage', {
                      rules: [
                        {
                          required: true,
                          message: '请输入小数点不超过2位的数字',
                          pattern: /^-?\d+\.?\d{0,2}$/,
                        },
                      ],
                    })(
                      <InputNumber
                        min={0}
                        max={99999999.99}
                        placeholder="请输入"
                        style={{ width: '100%' }}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="试用期劳动报酬">
                    {getFieldDecorator('probtnWage', {
                      rules: [
                        {
                          required: false,
                          message: '请输入小数点不超过2位的数字',
                          pattern: /^-?\d+\.?\d{0,2}$/,
                        },
                      ],
                    })(
                      <InputNumber
                        min={0}
                        max={99999999.99}
                        placeholder="请输入"
                        style={{ width: '100%' }}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="工时">
                    {getFieldDecorator('laborHour', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <Select placeholder="请选择" showSearch>
                        {dictOL(workHoursList)}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="岗位">
                    {getFieldDecorator('wkJob', {
                      rules: [{ required: true, message: '最多不超过50字符', max: 50 }],
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="工作地点">
                    {getFieldDecorator('wkLoc', {
                      rules: [{ required: true, message: '最多不超过100字符', max: 100 }],
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="工作内容">
                    {getFieldDecorator('wkContent', {
                      rules: [{ required: false, message: '最多不超过100字符', max: 100 }],
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="是否做入职体检">
                    {getFieldDecorator('entryMedExamFlag', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                      <Select placeholder="请选择" showSearch disabled>
                        {dictOL(yesNoList)}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
          </Spin>
          <FooterToolbar style={{ width: '100%' }}>
            <Button
              onClick={() => router.push(`${tempUrl}/index?activeKey=${activeKey}`)}
              style={{ marginRight: 10 }}
            >
              取消
            </Button>
            <Button type="primary" onClick={this.submitAll}>
              提交
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default BasicForm;
